package com.synjones.handsetS8;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Handler;

import com.finger.FingerModule;
import com.finger.FingerUtil;
import com.synjones.cardutil.util;
import com.synjones.hymodule.Bytes2Bmp;

/**
 * Created by zhaodianbo on 2016-8-22.
 */
public class S8HyFpUsbModule implements FingerprintReaderInterface {
    //声明设备
    Context context;
    Handler outHandler;

    Bitmap fpBmp;
    String fingerPhotoPath;

    private  byte[] fingerTemplate ;// 指纹模板
    private  byte[] fingerFeature ;// 指纹特征
    static byte[] fingerImage = new byte[256 * 360];// 指纹图像数据
    final int MSG_WHAT_SHOW_IMG=4321;

    int sensorType=1;//1=大指纹头，2=小指纹头
    private int templateOK;
    volatile boolean isScaning=false;
    final int SCAN_FINGER_TIMEOUT=5000;
    final int SPEED_LEVEL_OF_GET_IMAGE=1;
    final int SCAN_FINGER_COUNT=1;

    public S8HyFpUsbModule(Context context, Handler handler){
        this.context=context;
        outHandler=handler;
        //fingerPhotoPath= context.getFileStreamPath("fingerPhoto").getAbsolutePath();//Environment.getExternalStorageDirectory().getPath()+"/fp";
    }
    @Override
    public void powerOn() {
        if(WtWdPowerUtils.getFingerUSBPower(context)!=1)
            WtWdPowerUtils.setFingerUSBPower(context);
        FingerUtil.getSingleton().open(context);// 请求一次权限
       // WtWdPowerUtils.setFingerUSBPower(context);
   /*     try {
            Thread.sleep(500);//使模块上电完成
        } catch (InterruptedException e) {}*/
    }

    @Override
    public void powerOff() {
        close();
        WtWdPowerUtils.closeFingerUSBPower(context);//关闭
    }

    @Override
    public int open() {
        FingerUtil fingerUtil = FingerUtil.getSingleton();
        long t=System.currentTimeMillis();
        while(System.currentTimeMillis()-t<1000){
            fingerUtil.open(context);
            if (fingerUtil.getFd() != -1)
            {
                return 0;
            }
            util.mSleep(100);
        }
        return -1;
    }

    public int getSensorType(){
        return sensorType;
    }


    @Override
    public int close() {
        return 0;
    }

    @Override
    public int cleanFpFeature() {
        fingerFeature=null;
        fingerTemplate=null;
        return 0;
    }

    @Override
    public FpFeature getFpFeature(boolean showFpImage) {

        templateOK = 0;
        long t=System.currentTimeMillis();
        FingerUtil fingerUtil = FingerUtil.getSingleton();
        fingerUtil.open(context);

        FingerModule fingerModule = new FingerModule();

        if (fingerUtil.getFd() == -1)
        {
             sendMsg(MESSAGE_UPDATE_STATUS,"连接指纹模块失败");
            return null;
        }

        int ret = fingerModule.xdev_init(fingerUtil.getFd());
        if (ret <= 0)
        {
             sendMsg(MESSAGE_UPDATE_STATUS,"打开指纹模块错误：" + ret);

            fingerModule.xdev_exit();
            return null;
        }
        else
        {
             sendMsg(MESSAGE_UPDATE_STATUS,"打开指纹模块成功：" + ret);
        }

        byte[] templatebuffer = new byte[1024];
        byte[] featurebuffer = new byte[248];

        fingerModule.xdev_SetSpeedOfGetImageAndMinutiae(SPEED_LEVEL_OF_GET_IMAGE);
        fingerModule.template_start();
        int quality=0;
        float points=0;
        isScaning=true;
        while (isScaning)
        {
             sendMsg(MESSAGE_UPDATE_STATUS,"请放置手指");

            int result = fingerModule.xdev_getImageAndFeature(SCAN_FINGER_TIMEOUT,fingerImage, featurebuffer);
            int imageW = fingerModule.xdev_imgW();
            int imageH = fingerModule.xdev_imgH();

            if (result == 1)
            {
                //
                // 这里可以添加显示指纹图像函数，开发者完善
                //
                fpBmp = Bytes2Bmp.genBitmap(imageW, imageH, fingerImage);
                sendMsg(MSG_WHAT_SHOW_IMG,fpBmp);

                result = fingerModule.xdev_getTemplate(SCAN_FINGER_COUNT,templatebuffer);

                // 采集指纹模板成功
                if (result == 2)
                {

                    fingerTemplate = templatebuffer;
                    quality=fingerModule.xdev_CalQuality();
                    points=(float) (fingerModule.xdev_GetValidPoints()*100)/(float)(imageH*imageW);
                     sendMsg(MESSAGE_UPDATE_STATUS,"获取指纹模板成功");

                   // result = fingerModule.xdev_waitleft();

                    templateOK = 1;

                    break;
                }
                else if (result == 1)
                {
                     sendMsg(MESSAGE_UPDATE_STATUS,"扫描成功，请移开手指");

                    result = fingerModule.xdev_waitleft();
                    if (result != 1)
                    {
                         sendMsg(MESSAGE_UPDATE_STATUS,"设备错误");
                        break;
                    }
                    continue;
                }
                else
                {
                     sendMsg(MESSAGE_UPDATE_STATUS,"未知错误, result = " + result);
                    break;
                }
            }
            else if (result == 0)
            {
                //可能是连接问题 并未超时
                if((System.currentTimeMillis()-t) < SCAN_FINGER_TIMEOUT/2)
                    continue;
                 sendMsg(MESSAGE_UPDATE_STATUS,"录入超时");
                break;
            }
            else
            {
                 sendMsg(MESSAGE_UPDATE_STATUS,"设备错误");
                break;
            }
        }

        fingerModule.xdev_exit();
        fingerUtil.close();
        isScaning=false;
        if(templateOK==1)
            return new FpFeature(fpBmp,fingerTemplate,""/*+(System.currentTimeMillis()-t)+","+quality+","+String.format("%.1f",points)*/);
        return null;
    }


    @Override
    public int setFpFeature(int toWhere, byte[] data) {
        try{
            if(data==null)
                return -1;
            //身份证指纹特征值512字节，其他值为自身特征值248字节
            if(data.length==512){
                fingerTemplate=new byte[512];
                System.arraycopy(data,0, fingerTemplate, 0, 512);
                return 0;
            }else if ((data.length==1024)){
                fingerTemplate=new byte[1024];
                System.arraycopy(data,0, fingerTemplate, 0, 1024);
            }else if(data.length==248){
                fingerFeature=new byte[248];
                fingerTemplate=null;
                System.arraycopy(data,0, fingerFeature, 0, 248);
            }else {
                return -1;
            }
            return 0;
        }catch (Exception e){
        }
        return -1;
    }

    @Override
    public FpVerifyResult verifyFp(int sThreshold) {

        if (fingerTemplate == null && fingerFeature == null)
        {
            sendMsg(MESSAGE_UPDATE_STATUS,"请先录入指纹或下载模板!");
            return null;
        }

        FingerUtil fingerUtil = FingerUtil.getSingleton();
        fingerUtil.open(context);

        FingerModule fingerModule = new FingerModule();

        if (fingerUtil.getFd() == -1)
        {
            //没有获取到设备连接
            sendMsg(MESSAGE_UPDATE_STATUS,"请在弹出询问使用USB设备对话框时允许使用");
            return null;
        }
        //初始化
        int ret = fingerModule.xdev_init(fingerUtil.getFd());

        if (ret <= 0)
        {
            //打开设备失败
            sendMsg(MESSAGE_UPDATE_STATUS,"打开指纹模块错误：" + ret);
            fingerModule.xdev_exit();
            return null;
        }
        else
        {
            //打开设备成功
            sendMsg(MESSAGE_UPDATE_STATUS,"打开指纹模块成功：" + ret);
        }

        //初始化
        isScaning=true;

        sendMsg(MESSAGE_UPDATE_STATUS,"请放置手指");
        isScaning=true;
        byte[] featurebuffer = new byte[248];

        fingerModule.xdev_SetSpeedOfGetImageAndMinutiae(SPEED_LEVEL_OF_GET_IMAGE);
        fingerModule.template_start();
        //采集指纹特征
        int result = fingerModule.xdev_getImageAndFeature(SCAN_FINGER_TIMEOUT,fingerImage, featurebuffer);
        int imageW = fingerModule.xdev_imgW();
        int imageH = fingerModule.xdev_imgH();

        if (result == 1)
        {
            //采集指纹特征成功
            sendMsg(MESSAGE_UPDATE_STATUS,"采集成功");
            Bitmap baseBitmap = Bytes2Bmp.genBitmap(imageW, imageH, fingerImage);
            sendMsg(MSG_WHAT_SHOW_IMG,baseBitmap);
            result=-1;

            if(fingerTemplate!=null && fingerTemplate.length==512){//二代证指纹对比
                sendMsg(MESSAGE_UPDATE_STATUS,"开始对比二代证指纹");
                result = fingerModule.xdev_recognition_fingerGAB(fingerTemplate,featurebuffer,sThreshold);
            }else if(fingerTemplate!=null && fingerTemplate.length==1024){
                //fingerFeature = featurebuffer;
                sendMsg(MESSAGE_UPDATE_STATUS,"开始对比指纹");
                result = fingerModule.xdev_recognition_finger(fingerTemplate, featurebuffer, sThreshold);
            }else if(fingerFeature!=null && fingerFeature.length==248){
                byte[] templatebuffer = new byte[1024];
                result = fingerModule.xdev_getTemplate(SCAN_FINGER_COUNT,templatebuffer);
                if(result==2){
                    result = fingerModule.xdev_recognition_finger(templatebuffer, fingerFeature, sThreshold);
                }
            }

            if (result == 1)
            {
                sendMsg(MESSAGE_UPDATE_STATUS,"比对成功"); // showDialog
                isScaning = false;
                fingerModule.xdev_exit();
                fingerUtil.close();
                return new FpVerifyResult(true,100,0);
            }
            else if (result == 0)
            {
                sendMsg(MESSAGE_UPDATE_STATUS,"比对失败");
            }
            else
            {
                sendMsg(MESSAGE_UPDATE_STATUS,"指纹数据错误,result="+result);
            }

        }
        else
        {
            if (result == 0)
            {
                //超时
                sendMsg(MESSAGE_UPDATE_STATUS,"扫描指纹超时");
            }
            else
            {
                //设备错误
                sendMsg(MESSAGE_UPDATE_STATUS,"设备错误,result="+result);
            }
        }
        isScaning = false;
        fingerModule.xdev_exit();
        fingerUtil.close();
        return new FpVerifyResult(false,0,0);
    }

    @Override
    public void cancel() {
        while (isScaning)
            util.mSleep(50);
    }

    @Override
    public int calibration() {
        return -1;
    }


    private void sendMsg(int what,Object msg){
        if(outHandler!=null)
            outHandler.obtainMessage(what,msg).sendToTarget();
    }


}
